package de.jtserver;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import de.jtserver.model.JTalkScript;

public class JTalkDAO {
	EntityManager _em;
	
	static Logger logger = Logger.getLogger("de.jtserver.JTalkDAO");
	
	public JTalkDAO() {
		_em = EMF.get().createEntityManager();
	}

	public List findByOwner(String owner) {
		Query q = _em.createQuery("select from " + JTalkScript.class.getName() + " where owner = '" + owner
				+ "' order by id desc limit 1");
		return q.getResultList();
	}
	
	public JTalkScript save(String owner, String script, Object smalltalk) {
		JTalkScript jts = new JTalkScript();
		jts.setOwner(owner);
		jts.setScript(script);
		
		save(jts);
		return jts;
	}
	
	public JTalkScript save(String owner, String script) {
		JTalkScript jts = new JTalkScript();
		jts.setOwner(owner);
		jts.setScript(script);
		save(jts);
		return jts;
	}
	
	public JTalkScript save(JTalkScript jts) {
		_em.getTransaction().begin();
		logger.warning("persisting ...");
		_em.persist(jts);
		logger.warning("committing transaction ...");
		_em.getTransaction().commit();
		logger.warning("closing em");
		return jts;
	}


	
}
